<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改库存-入库信息')" />

    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-editable-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-in-edit" th:object="${scmInventoryIn}">
            <input name="id" th:field="*{id}" type="hidden">
            <div class="form-group">
                <label class="col-sm-3 control-label">单据编号：</label>
                <div class="col-sm-8">
                    <input name="code" id="code" th:field="*{code}" class="form-control"></input>

                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">单据主题-名称：</label>
                <div class="col-sm-8">
                    <input name="name" id="name" th:field="*{name}" class="form-control"></input>

                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">单据日期 ：</label>
                <div class="input-group date col-sm-8 " style="padding-right:15px;padding-left:15px">
                    <span class="input-group-addon" ><i class="fa fa-calendar"></i></span>
                    <input type="text"  name="inDatetime" class="form-control" th:field="*{inDatetimeStr}" id="datetimepicker-demo-2" placeholder="yyyy-MM-dd">
                </div>


            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">供应商名称：</label>
                <div class="col-sm-8">

                    <span id ="supplierNameSpan" name ="supplierNameSpan" th:text="*{supplierName}"></span>

                    <input name="supplierName" id="supplierName" type="hidden"  th:field="*{supplierName}"/>

                    <input name="supplierId" id="supplierId" type="hidden"  th:field="*{supplierId}"/>

                    <a class="btn btn-primary" onclick="querySupplier()">
                        <i class="fa btn-success"></i> 选择供应商
                    </a>
                </div>
            </div>



            <div class="form-group">
                <label class="col-sm-3 control-label">业务员-name：</label>
                <div class="col-sm-8">
                    <input name="salesmanName" id="salesmanName" th:field="*{salesmanName}" class="form-control"></input>

                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">采购订单-id：</label>
                <div class="col-sm-8">
                    <input name="purchaseOrderId" th:field="*{purchaseOrderId}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">备注：</label>
                <div class="col-sm-8">
                    <input name="remark" th:field="*{remark}" class="form-control" type="text">
                </div>
            </div>



        <div class="btn-group-sm pull-right"  role="group">

            <a class="btn btn-primary" onclick="saveInStash()">
                <i class="fa fa-edit"></i> 保存入库单
            </a>
        </div>


        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-primary" onclick="addData()">
                <i class="fa btn-success"></i> 添加商品明细
            </a>

        </div>


        <div class="row">
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
        </form>

    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-table-editable-js" />

    <th:block th:include="include :: bootstrap-suggest-js" />
    <th:block th:include="include :: bootstrap-typeahead-js" />
    <script th:src="@{/js/jquery.tmpl.js}"></script>


    <script th:inline="javascript">
        var prefix = ctx + "scm/inventory/in";


        var allStash=[];

        $(function() {
            <!-- datetimepicker示例  th:field="*{inDatetimeStr}"  -->

            $("#datetimepicker-demo-2").datetimepicker({
                format: "yyyy-mm-dd",
                minView: "month",
                autoclose: true
            });

            queryAllStash();
            console.log(allStash);

            var id = $("#id").val();
            if(id==null||id==''){
                id=0;
            }
            var options = {
                url:   prefix+"/detail/list?id="+id,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                    {
                        field: 'index',
                        align: 'center',
                        title: "序号",
                        formatter: function (value, row, index) {
                            var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumber(index));
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].id' value='%s'>", index, row.id);
                            return columnIndex + $.table.serialNumber(index) + columnId;
                        }
                    },
                    {
                        field: 'productId',
                        align: 'center',
                        title: "商品ID",
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productId' value='%s'>", index, row.productId);
                            return columnId +row.productId;
                        }

                    },

                    {
                        field: 'productCode',
                        align: 'center',
                        title: "商品编码",
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productCode' value='%s'>", index, row.productCode);
                            return columnId +row.productCode;
                        }
                    },

                    {
                        field : 'productName',
                        align: 'center',
                        title : '商品名称',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productName' value='%s'>", index, row.productName);
                            return columnId +row.productName;
                        }
                    },

                    {
                        field: 'brand',
                        title: '品牌 ',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].brand' value='%s'>", index, row.brand);
                            return columnId +row.brand;
                        }
                    },
                    {
                        field: 'source',
                        title: '商品来源',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].source' value='%s'>", index, row.source);
                            return columnId +row.source;
                        }
                    },

                    {
                        field : 'productUnit',
                        title : '商品单位',
                        formatter: function (value, row, index) {
                            var columnId = $.common.sprintf("<input type='hidden' name='products[%s].productUnit' value='%s'>", index, row.productUnit);
                            return columnId +row.productUnit;
                        }
                    },
                    {
                        field: 'stashId',
                        title: '入库仓库',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var data = { stashs: allStash, stashId: value,index: index };
                            return $("#stashSelect").tmpl(data).html();
                        }

                    },
                    {
                        field: 'productCount',
                        align: 'center',
                        title: '商品数量',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control goodsWeight' type='text' id='productCount%s' name='products[%s].productCount' value='%s'>", index,index, value);
                            return html;
                        }
                    },
                    {
                        field: 'inStashAmount',
                        align: 'center',
                        title: '入库价格',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='inStashAmount%s' name='products[%s].inStashAmount' value='%s'>", index,index, value);
                            return html;
                        }
                    },
                    {
                        field: 'remark',
                        align: 'center',
                        title: '备注',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control' type='text' id='remark%s'  name='products[%s].remark' value='%s'>", index,index, value);
                            return html;
                        }
                    },

                    {
                        title: '操作',
                        align: 'center',
                        formatter: function(value, row, index) {
                            var actions = [];
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeData(\'' + index + '\')"><i class="fa fa-remove"></i>删除</a>');
                            return actions.join('');
                        }
                    }]
            };
            $.table.init(options);

        });

        $("#form-in-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-in-edit').serialize());
            }
        }


        function onEditableSave (field, row, rowIndex, oldValue, $el) {

            // alert("字段名：" + field + "，当前值：" + row[field]  + "，旧值：" + oldValue);

        }

        /* 查询表格所有数据值 */
        function getData(){
            var data = $("#" + table.options.id).bootstrapTable('getData');
            // alert(JSON.stringify(data))
            return data;
        }

        /* 查询表格选择行数据值 */
        function getSelections(){
            var data = $("#" + table.options.id).bootstrapTable('getSelections');
            // alert(JSON.stringify(data))
        }



        function addData(){
            // $.modal.closeTab();

            $.operate.selectProduct("/scm/product/popupListPage",selectProductCallback);

            // $("#" + table.options.id).bootstrapTable('append',newRow);

        }

        function selectProductCallback(productId) {

            console.log("selectProductCallback"+productId);

            var config = {
                url: ctx+"scm/product/detail/"+productId,
                type: "post",
                dataType: "json",
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {

                    addProduct(result.data);
                    $.modal.closeLoading();
                }
            };
            $.ajax(config);

        }


        function querySupplier(){
            // $.modal.closeTab();

            $.operate.selectProduct("/system/supplier/popupListPage",selectSupplierCallback);

            // $("#" + table.options.id).bootstrapTable('append',newRow);

        }
        function selectSupplierCallback(id) {

            console.log("selectSupplierCallback="+id);

            var config = {
                url: ctx+"system/supplier/detail/"+id,
                type: "post",
                dataType: "json",
                data: null,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                success: function(result) {

                    console.log(result);
                    console.log(result.data);

                    $("#supplierNameSpan").html(result.data.name);
                    $("#supplierName").val(result.data.name);
                    $("#supplierId").val(result.data.id)

                    $.modal.closeLoading();
                }
            };
            $.ajax(config);

        }

        function queryAllStash() {

            var config = {
                url: ctx+"scm/inventory/stash/queryAll",
                type: "post",
                dataType: "json",
                async: false,
                data: null,
                success: function(result) {
                    allStash =result.data;
                }
            };
            $.ajax(config);
        }



        function addProduct(productData) {

            var count = $("#" + table.options.id).bootstrapTable('getData').length;

            var newRow = {
                index: $.table.serialNumber(count),
                productId: productData.id,
                productCode: productData.productCode,
                productName: productData.productName,
                brand: productData.brand,
                source: productData.source,
                productUnit: productData.productUnit,
                inStashAmount:'',
                productCount: '',
                remark: '',
            };

            sub.addRow(newRow);
        }


        function removeData(index){

            var data = $("#" + table.options.id).bootstrapTable('getData');
            data.splice(index, 1);

            $("#" + table.options.id).bootstrapTable('load', data);

        }

        function saveInStash(){

            var data = $("#form-in-edit").serializeArray();

            var productData = getData();

            if(productData.length==0){
                $.modal.alertError("请录入入库商品信息");
                return;
            }

            for (let i = 0; i <productData.length ; i++) {
                var stashId = $('#stashId'+i).val();
                var productCount =  $('#productCount'+i).val();
                var inStashAmount =  $('#inStashAmount'+i).val();

                var c = i+1;
                if(stashId==null||stashId==undefined||stashId==0||stashId=="0"){
                    $.modal.alertError("第("+c+")行请录入入库商品仓库信息");
                    return ;
                }
                if(productCount==null||productCount==undefined||productCount==""){
                    $.modal.alertError("第("+c+")行请录入入库商品数量信息");
                    return ;
                }
                if(inStashAmount==null||inStashAmount==undefined||inStashAmount==""){
                    $.modal.alertError("第("+c+")行请录入入库商品入库价格信息");
                    return ;
                }

            }

            var config = {
                url: ctx+"scm/inventory/in/save",
                type: "post",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍候...");
                },
                // contentType: "application/json;charset=UTF-8",
                success: function(result) {
                    console.log(result);

                    $.modal.alertSuccess("保存成功");
                    $.modal.closeTab();
                }
            };
            $.ajax(config);

        }

        function formToJson(form) {
            var formArray = form.serializeArray();
            var jsonObj = {};

            formArray.forEach(function(item) {
                jsonObj[item.name] = item.value;
            });

            return jsonObj;
        }
    </script>



    <!-- 仓库下拉列表 -->
    <script id="stashSelect" type="text/x-jquery-tmpl">
<div>
<select class='form-control' id='stashId${index}' name='products[${index}].stashId'>
      <option value="0">请选择</option>
    {{each(i,stash) stashs}}
     <option value={{= stash.value}}  {{if stashId===stash.value}}selected{{/if}} >{{= stash.text}}</option>
    {{/each}}
</select>
</div>
</script>

</body>
</html>
